<?php
	
/**
 * [weliam] Copyright (c) 2016/3/23 
 * 团model
 */
defined('IN_IA') or exit('Access Denied');
/**
 * 函数getgroupList，按检索条件检索出所有团
 * $params : 类型：array
 * 
 */
	function group_get_list($args = array()) {
		global $_W;
		
		$usepage = !empty($args['usepage'])? $args['usepage'] : false;
		$page = !empty($args['page'])? intval($args['page']): 1;
		$pagesize = !empty($args['pagesize'])? intval($args['pagesize']): 10;
		$orderby = !empty($args['orderby'])? $args['orderby'] : 'order by id desc';
		
		$condition = ' and `uniacid` = :uniacid';
		$params = array(':uniacid' => $_W['uniacid']);
		
		
		if ($usepage) {
			$sql = "SELECT * FROM " . tablename('tg_group') . " where 1 {$condition} {$orderby} LIMIT " . ($page - 1) * $pagesize . ',' . $pagesize;
		} else {
			$sql = "SELECT * FROM " . tablename('tg_group') . " where 1 {$condition} ";
		} 
		
		$list = pdo_fetchall($sql, $params);
		foreach($list as $key=>&$value){
			$value['gimg'] = tomedia($value['gimg']);
			$value['a'] = app_url('group/detail/display',array('id'=>$value['id']));
		}
		$total = pdo_fetchcolumn('SELECT COUNT(*) FROM '.tablename('tg_group')."where 1 $condition ",$params);
		
		$data = array();
		$data['list'] = $list;
		$data['total'] = $total;
		return $data;
	} 
/**
 * 函数getgroupByParams，按检索条件检索出指定团
 * $params : 类型：字符串
 * 
 */

function group_get_by_params($params = '') {
		global $_W;
		if(!empty($params)){
			$params = ' where '. $params;
		}
		$sql = "SELECT * FROM " . tablename('tg_group') . $params;
		$group = pdo_fetch($sql);
		return $group;
	}
/**
 * 函数getgroupByParams，按条件检索更新团
 * $data : 类型：array ; $params 类型：array
 * 
 */
function group_update_by_params($data,$params) {
		global $_W;
		$flag = pdo_update('tg_group',$data,$params);
		return $flag;
	}
/**
 * 函数insertgroup，插入新团
 * $data : 类型：array 
 * 返回值：插入ID
 */
function group_insert($data) {
		global $_W;
		$flag = pdo_insert('tg_group',$data);
		if($flag){
			$insertid = pdo_insertid();
		}else{
			$insertid = FALSE;
		}
		return $insertid;
	}
/**
 * 函数deletegroup，删除团
 * $id : 类型：int 
 * 返回值：
 */
function group_delete($id) {
		global $_W;
		$flag = pdo_delete('tg_group',$id);
		return $flag;
	}

	function updategourp() {
		global $_W;
		$now = time();
		$allgroups = pdo_fetchall("select * from" . tablename('tg_group') . "where groupstatus=3 and uniacid='{$_W['uniacid']}'");
		foreach ($allgroups as $key => $value) {
			if ($value['endtime'] < $now && $value['lacknum'] > 0) {

				if($value['on_success']==0)
				{
					if($value['selltype']!=4){
						pdo_update('tg_group', array('groupstatus' => 1), array('groupnumber' => $value['groupnumber']));
						$orders = pdo_fetchall("select id from" . tablename('tg_order') . "where tuan_id='{$value['groupnumber']}' and uniacid='{$_W['uniacid']}' and status=1");
						foreach ($orders as $k => $v) {
							$res = pdo_update('tg_order', array('status' => 10), array('id' => $v['id']));
						}
					}else{

						pdo_update('tg_group', array('groupstatus' => 2), array('groupnumber' => $value['groupnumber']));
						$orders = pdo_fetchall("select id,g_id,orderno,gnum from" . tablename('tg_order') . "where tuan_id=:tuan_id and uniacid=:uniacid and ptime>0",array(':tuan_id'=>$value['groupnumber'],':uniacid'=>$_W['uniacid']));
						$auto_orders = pdo_fetchall("select id from" . tablename('tg_order') . "where tuan_id=:tuan_id and uniacid=:uniacid and status=3",array(':tuan_id'=>$value['groupnumber'],':uniacid'=>$_W['uniacid']));

						$allnum=count($orders)+count($auto_orders);
						foreach ($orders as $k => $v) {
							//$goodsInfo = pdo_fetch("select id,group_level,gprice from" . tablename('tg_goods') . "where id=:id and uniacid=:uniacid ",array(':id'=>$v['g_id'],':uniacid'=>$_W['uniacid']));
							
							$param_level = unserialize($value['group_level']);
							for($i=0;$i<count($param_level)-1;$i++){
								for($j=0;$j<count($param_level)-$i-1;$j++){
									if($param_level[$j]['groupnum']<$param_level[$j+1]['groupnum']){
										$temp=$param_level[$j]; 
										$param_level[$j] = $param_level[$j+1];
										$param_level[$j+1]= $temp;
									}
								}
							}
							for($i=0;$i<count($param_level)-1;$i++){
																	
											if($param_level[$i]['groupnum']>$allnum&&$param_level[$i+1]['groupnum']<=$allnum)
											{
												$tempprice=$param_level[$i+1]['groupprice'];
												break;
											}
											if($param_level[$i]['groupnum']==$allnum)
											{
												$tempprice=$param_level[$i]['groupprice'];
												break;
											}
										}
									
											if($param_level[count($param_level)-1]['groupnum']>=$allnum)
											{
												$tempprice=$param_level[count($param_level)-1]['groupprice'];
												
											}

										$refundprice=(round($value['price'] ,2)-round($tempprice ,2))*$v['gnum'];
										if($refundprice>0)
										{
											//插入退款记录
											if($v['orderno']!='20160929382019210903')
											{
												$data1 = array('orderno' => $v['orderno'], 'status' => 1,'refundprice'=>$refundprice);
												pdo_insert('tg_order_level_refund', $data1);
											}
											
										}										
										
										
						}
						order_update_by_params(array('status' => 8,'successtime'=>TIMESTAMP), array('tuan_id' => $value['groupnumber'], 'status' => 1));
						if($value['groupnumber']!=532601) {
							group_success($value['groupnumber'], '');
							wl_load()->func('print');
							alltuan_print($value['groupnumber']);
						}
					}
				}
				if($value['on_success']==1)
				{
					pdo_update('tg_group', array('groupstatus' => 2,'successtime'=>TIMESTAMP), array('groupnumber' => $value['groupnumber']));
					if($value['selltype']==7)
					{
						order_update_by_params(array('successtime'=>TIMESTAMP,'bukuanstatus'=>1), array('tuan_id' => $value['groupnumber'], 'status' => 1));
						//补款通知
						$order_list=pdo_fetchall('select orderno,openid,goodsname,ptime from'.tablename('tg_order').'where tuan_id=:tuan_id and status=1',array(':tuan_id'=>$value['groupnumber']));
						foreach($order_list as $item)
						{

							$url = app_url('order/master_orderconfirm', array('master_orderno' => $item['orderno']));
							$openid=$item['openid'];
							$title='您好，你参与的'.$item['goodsname'].'的拼团，可以补齐尾款了';
							$goodsname=$item['goodsname'];
							$orderno=$item['orderno'];
							$datetime=date('Y-m-d H:i',$item['ptime']);
							$remark='请在'.$item['goodsname'].'活动结束之前补齐尾款，过时失效系统将自动退款处理';
							bukuan_notice($openid,$title,$goodsname,$orderno,$datetime,$remark,$url);
						}

					}else{
						order_update_by_params(array('status' => 8,'successtime'=>TIMESTAMP), array('tuan_id' => $value['groupnumber'], 'status' => 1));
						/*团成功通知*/
						if($value['groupnumber']!=532601)
						{
							group_success($value['groupnumber'],'');
							wl_load()->func('print');
							alltuan_print($value['groupnumber']);
						}

					}

				}
				
				
			}
		}
	}	
